<template>
  <div class="docs">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="docs-header">
          <div class="header-content">
            <h1>API接口文档</h1>
            <p>完整的后端API接口文档，包含请求参数、响应格式和示例代码</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="6">
        <el-card class="sidebar-card">
          <template #header>
            <span>接口分类</span>
          </template>
          
          <el-menu
            :default-active="activeCategory"
            @select="handleCategorySelect"
            class="category-menu"
          >
            <el-menu-item 
              v-for="category in categories" 
              :key="category.key" 
              :index="category.key"
            >
              <el-icon><component :is="category.icon" /></el-icon>
              <span>{{ category.name }}</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <el-card class="content-card">
          <template #header>
            <div class="content-header">
              <span>{{ currentCategory?.name || '选择接口分类' }}</span>
              <el-button 
                v-if="currentCategory" 
                type="primary" 
                @click="testApi"
                icon="Connection"
              >
                测试接口
              </el-button>
            </div>
          </template>
          
          <div v-if="currentCategory" class="api-content">
            <div v-for="api in currentCategory.apis" :key="api.name" class="api-item">
              <el-divider content-position="left">
                <h3>{{ api.name }}</h3>
              </el-divider>
              
              <el-descriptions :column="2" border class="api-info">
                <el-descriptions-item label="接口地址">
                  <el-tag type="primary">{{ api.url }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="请求方法">
                  <el-tag :type="getMethodColor(api.method)">{{ api.method }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="接口描述" :span="2">
                  {{ api.description }}
                </el-descriptions-item>
              </el-descriptions>
              
              <div class="api-details">
                <el-tabs v-model="api.activeTab" type="border-card">
                  <el-tab-pane label="请求参数" name="params">
                    <div v-if="api.params && api.params.length > 0">
                      <el-table :data="api.params" border style="width: 100%">
                        <el-table-column prop="name" label="参数名" width="150" />
                        <el-table-column prop="type" label="类型" width="100" />
                        <el-table-column prop="required" label="必填" width="80">
                          <template #default="scope">
                            <el-tag :type="scope.row.required ? 'danger' : 'info'">
                              {{ scope.row.required ? '是' : '否' }}
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="description" label="说明" />
                        <el-table-column prop="example" label="示例" width="150" />
                      </el-table>
                    </div>
                    <el-empty v-else description="无请求参数" />
                  </el-tab-pane>
                  
                  <el-tab-pane label="响应格式" name="response">
                    <div class="response-format">
                      <h4>成功响应 (200)</h4>
                      <el-input
                        v-model="api.responseExample"
                        type="textarea"
                        :rows="8"
                        readonly
                        class="response-example"
                      />
                      
                      <h4>响应字段说明</h4>
                      <el-table :data="api.responseFields" border style="width: 100%">
                        <el-table-column prop="name" label="字段名" width="150" />
                        <el-table-column prop="type" label="类型" width="100" />
                        <el-table-column prop="description" label="说明" />
                        <el-table-column prop="example" label="示例" width="150" />
                      </el-table>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="示例代码" name="code">
                    <div class="code-examples">
                      <el-tabs v-model="api.codeTab" type="card">
                        <el-tab-pane label="JavaScript" name="javascript">
                          <pre class="code-block">{{ api.codeExamples.javascript }}</pre>
                        </el-tab-pane>
                        <el-tab-pane label="Python" name="python">
                          <pre class="code-block">{{ api.codeExamples.python }}</pre>
                        </el-tab-pane>
                        <el-tab-pane label="cURL" name="curl">
                          <pre class="code-block">{{ api.codeExamples.curl }}</pre>
                        </el-tab-pane>
                      </el-tabs>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="错误码" name="errors">
                    <el-table :data="api.errorCodes" border style="width: 100%">
                      <el-table-column prop="code" label="错误码" width="100" />
                      <el-table-column prop="message" label="错误信息" />
                      <el-table-column prop="description" label="说明" />
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
          
          <div v-else class="no-category">
            <el-empty description="请选择左侧的接口分类" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  User, 
  Document, 
  Setting, 
  DataAnalysis,
  Tools,
  Monitor
} from '@element-plus/icons-vue'

const router = useRouter()
const activeCategory = ref('user')

// 接口分类数据
const categories = ref([
  {
    key: 'user',
    name: '用户管理',
    icon: 'User',
    apis: [
      {
        name: '获取用户列表',
        url: '/api/users',
        method: 'GET',
        description: '获取系统中的所有用户列表，支持分页和搜索',
        activeTab: 'params',
        params: [
          { name: 'page', type: 'integer', required: false, description: '页码，默认为1', example: '1' },
          { name: 'size', type: 'integer', required: false, description: '每页数量，默认为10', example: '10' },
          { name: 'keyword', type: 'string', required: false, description: '搜索关键词', example: '张三' },
          { name: 'status', type: 'string', required: false, description: '用户状态', example: 'active' }
        ],
        responseExample: JSON.stringify({
          code: 200,
          message: "success",
          data: {
            users: [
              { id: 1, username: "zhangsan", email: "zhangsan@example.com", status: "active" },
              { id: 2, username: "lisi", email: "lisi@example.com", status: "inactive" }
            ],
            total: 2,
            page: 1,
            size: 10
          }
        }, null, 2),
        responseFields: [
          { name: 'code', type: 'integer', description: '响应状态码', example: '200' },
          { name: 'message', type: 'string', description: '响应消息', example: 'success' },
          { name: 'data.users', type: 'array', description: '用户列表', example: '[]' },
          { name: 'data.total', type: 'integer', description: '总数量', example: '100' },
          { name: 'data.page', type: 'integer', description: '当前页码', example: '1' },
          { name: 'data.size', type: 'integer', description: '每页数量', example: '10' }
        ],
        codeTab: 'javascript',
        codeExamples: {
          javascript: `// 使用 fetch API
fetch('/api/users?page=1&size=10&keyword=张三')
  .then(response => response.json())
  .then(data => {
    console.log('用户列表:', data.data.users);
    console.log('总数:', data.data.total);
  })
  .catch(error => {
    console.error('获取用户列表失败:', error);
  });

// 使用 axios
const response = await axios.get('/api/users', {
  params: {
    page: 1,
    size: 10,
    keyword: '张三'
  }
});
console.log(response.data);`,
          python: `import requests

# 获取用户列表
response = requests.get('/api/users', params={
    'page': 1,
    'size': 10,
    'keyword': '张三'
})

if response.status_code == 200:
    data = response.json()
    users = data['data']['users']
    total = data['data']['total']
    print(f'用户列表: {users}')
    print(f'总数: {total}')
else:
    print(f'请求失败: {response.status_code}')`,
          curl: `curl -X GET "http://localhost:8080/api/users?page=1&size=10&keyword=张三" \\
  -H "Content-Type: application/json" \\
  -H "Authorization: Bearer YOUR_TOKEN"`
        },
        errorCodes: [
          { code: 400, message: 'Bad Request', description: '请求参数错误' },
          { code: 401, message: 'Unauthorized', description: '未授权访问' },
          { code: 403, message: 'Forbidden', description: '禁止访问' },
          { code: 500, message: 'Internal Server Error', description: '服务器内部错误' }
        ]
      },
      {
        name: '创建用户',
        url: '/api/users',
        method: 'POST',
        description: '创建新用户，需要提供用户基本信息',
        activeTab: 'params',
        params: [
          { name: 'username', type: 'string', required: true, description: '用户名', example: 'zhangsan' },
          { name: 'email', type: 'string', required: true, description: '邮箱地址', example: 'zhangsan@example.com' },
          { name: 'password', type: 'string', required: true, description: '密码', example: 'password123' },
          { name: 'fullName', type: 'string', required: false, description: '真实姓名', example: '张三' },
          { name: 'phone', type: 'string', required: false, description: '手机号码', example: '13800138000' }
        ],
        responseExample: JSON.stringify({
          code: 201,
          message: "用户创建成功",
          data: {
            id: 3,
            username: "zhangsan",
            email: "zhangsan@example.com",
            fullName: "张三",
            status: "active",
            createdAt: "2024-01-01T00:00:00Z"
          }
        }, null, 2),
        responseFields: [
          { name: 'code', type: 'integer', description: '响应状态码', example: '201' },
          { name: 'message', type: 'string', description: '响应消息', example: '用户创建成功' },
          { name: 'data.id', type: 'integer', description: '用户ID', example: '3' },
          { name: 'data.username', type: 'string', description: '用户名', example: 'zhangsan' },
          { name: 'data.email', type: 'string', description: '邮箱地址', example: 'zhangsan@example.com' },
          { name: 'data.status', type: 'string', description: '用户状态', example: 'active' },
          { name: 'data.createdAt', type: 'string', description: '创建时间', example: '2024-01-01T00:00:00Z' }
        ],
        codeTab: 'javascript',
        codeExamples: {
          javascript: `// 创建用户
const userData = {
  username: 'zhangsan',
  email: 'zhangsan@example.com',
  password: 'password123',
  fullName: '张三',
  phone: '13800138000'
};

fetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: JSON.stringify(userData)
})
.then(response => response.json())
.then(data => {
  console.log('用户创建成功:', data.data);
})
.catch(error => {
  console.error('创建用户失败:', error);
});`,
          python: `import requests
import json

# 用户数据
user_data = {
    'username': 'zhangsan',
    'email': 'zhangsan@example.com',
    'password': 'password123',
    'fullName': '张三',
    'phone': '13800138000'
}

# 创建用户
response = requests.post('/api/users', 
    json=user_data,
    headers={'Authorization': 'Bearer YOUR_TOKEN'}
)

if response.status_code == 201:
    data = response.json()
    print('用户创建成功:', data['data'])
else:
    print(f'创建失败: {response.status_code}')`,
          curl: `curl -X POST "http://localhost:8080/api/users" \\
  -H "Content-Type: application/json" \\
  -H "Authorization: Bearer YOUR_TOKEN" \\
  -d '{
    "username": "zhangsan",
    "email": "zhangsan@example.com",
    "password": "password123",
    "fullName": "张三",
    "phone": "13800138000"
  }'`
        },
        errorCodes: [
          { code: 400, message: 'Bad Request', description: '请求参数错误或用户名已存在' },
          { code: 401, message: 'Unauthorized', description: '未授权访问' },
          { code: 422, message: 'Validation Error', description: '数据验证失败' },
          { code: 500, message: 'Internal Server Error', description: '服务器内部错误' }
        ]
      }
    ]
  },
  {
    key: 'auth',
    name: '认证授权',
    icon: 'Setting',
    apis: [
      {
        name: '用户登录',
        url: '/api/auth/login',
        method: 'POST',
        description: '用户登录接口，返回访问令牌',
        activeTab: 'params',
        params: [
          { name: 'username', type: 'string', required: true, description: '用户名或邮箱', example: 'zhangsan' },
          { name: 'password', type: 'string', required: true, description: '密码', example: 'password123' }
        ],
        responseExample: JSON.stringify({
          code: 200,
          message: "登录成功",
          data: {
            token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
            refreshToken: "refresh_token_here",
            user: {
              id: 1,
              username: "zhangsan",
              email: "zhangsan@example.com",
              fullName: "张三"
            }
          }
        }, null, 2),
        responseFields: [
          { name: 'code', type: 'integer', description: '响应状态码', example: '200' },
          { name: 'message', type: 'string', description: '响应消息', example: '登录成功' },
          { name: 'data.token', type: 'string', description: '访问令牌', example: 'JWT_TOKEN' },
          { name: 'data.refreshToken', type: 'string', description: '刷新令牌', example: 'REFRESH_TOKEN' },
          { name: 'data.user', type: 'object', description: '用户信息', example: '{}' }
        ],
        codeTab: 'javascript',
        codeExamples: {
          javascript: `// 用户登录
const loginData = {
  username: 'zhangsan',
  password: 'password123'
};

fetch('/api/auth/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(loginData)
})
.then(response => response.json())
.then(data => {
  if (data.code === 200) {
    // 保存令牌
    localStorage.setItem('token', data.data.token);
    localStorage.setItem('refreshToken', data.data.refreshToken);
    console.log('登录成功:', data.data.user);
  }
})
.catch(error => {
  console.error('登录失败:', error);
});`,
          python: `import requests

# 登录数据
login_data = {
    'username': 'zhangsan',
    'password': 'password123'
}

# 用户登录
response = requests.post('/api/auth/login', json=login_data)

if response.status_code == 200:
    data = response.json()
    token = data['data']['token']
    refresh_token = data['data']['refreshToken']
    user = data['data']['user']
    print('登录成功:', user)
    print('访问令牌:', token)
else:
    print(f'登录失败: {response.status_code}')`,
          curl: `curl -X POST "http://localhost:8080/api/auth/login" \\
  -H "Content-Type: application/json" \\
  -d '{
    "username": "zhangsan",
    "password": "password123"
  }'`
        },
        errorCodes: [
          { code: 400, message: 'Bad Request', description: '请求参数错误' },
          { code: 401, message: 'Unauthorized', description: '用户名或密码错误' },
          { code: 429, message: 'Too Many Requests', description: '请求过于频繁' },
          { code: 500, message: 'Internal Server Error', description: '服务器内部错误' }
        ]
      }
    ]
  },
  {
    key: 'file',
    name: '文件管理',
    icon: 'Document',
    apis: [
      {
        name: '文件上传',
        url: '/api/files/upload',
        method: 'POST',
        description: '上传文件到服务器，支持多种文件格式',
        activeTab: 'params',
        params: [
          { name: 'file', type: 'file', required: true, description: '要上传的文件', example: 'document.pdf' },
          { name: 'category', type: 'string', required: false, description: '文件分类', example: 'document' },
          { name: 'description', type: 'string', required: false, description: '文件描述', example: '项目文档' }
        ],
        responseExample: JSON.stringify({
          code: 200,
          message: "文件上传成功",
          data: {
            fileId: "file_123456",
            fileName: "document.pdf",
            fileSize: 1024000,
            fileUrl: "https://example.com/files/document.pdf",
            uploadTime: "2024-01-01T00:00:00Z"
          }
        }, null, 2),
        responseFields: [
          { name: 'code', type: 'integer', description: '响应状态码', example: '200' },
          { name: 'message', type: 'string', description: '响应消息', example: '文件上传成功' },
          { name: 'data.fileId', type: 'string', description: '文件ID', example: 'file_123456' },
          { name: 'data.fileName', type: 'string', description: '文件名', example: 'document.pdf' },
          { name: 'data.fileSize', type: 'integer', description: '文件大小(字节)', example: '1024000' },
          { name: 'data.fileUrl', type: 'string', description: '文件访问URL', example: 'https://...' },
          { name: 'data.uploadTime', type: 'string', description: '上传时间', example: '2024-01-01T00:00:00Z' }
        ],
        codeTab: 'javascript',
        codeExamples: {
          javascript: `// 文件上传
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('category', 'document');
formData.append('description', '项目文档');

fetch('/api/files/upload', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  },
  body: formData
})
.then(response => response.json())
.then(data => {
  if (data.code === 200) {
    console.log('文件上传成功:', data.data);
    console.log('文件URL:', data.data.fileUrl);
  }
})
.catch(error => {
  console.error('文件上传失败:', error);
});`,
          python: `import requests

# 文件上传
with open('document.pdf', 'rb') as f:
    files = {'file': f}
    data = {
        'category': 'document',
        'description': '项目文档'
    }
    
    response = requests.post('/api/files/upload',
        files=files,
        data=data,
        headers={'Authorization': 'Bearer YOUR_TOKEN'}
    )

if response.status_code == 200:
    data = response.json()
    print('文件上传成功:', data['data'])
else:
    print(f'上传失败: {response.status_code}')`,
          curl: `curl -X POST "http://localhost:8080/api/files/upload" \\
  -H "Authorization: Bearer YOUR_TOKEN" \\
  -F "file=@document.pdf" \\
  -F "category=document" \\
  -F "description=项目文档"`
        },
        errorCodes: [
          { code: 400, message: 'Bad Request', description: '请求参数错误' },
          { code: 401, message: 'Unauthorized', description: '未授权访问' },
          { code: 413, message: 'Payload Too Large', description: '文件过大' },
          { code: 415, message: 'Unsupported Media Type', description: '不支持的文件格式' },
          { code: 500, message: 'Internal Server Error', description: '服务器内部错误' }
        ]
      }
    ]
  }
])

const currentCategory = computed(() => {
  return categories.value.find(cat => cat.key === activeCategory.value)
})

const handleCategorySelect = (key) => {
  activeCategory.value = key
}

const getMethodColor = (method) => {
  const colors = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return colors[method] || 'info'
}

const testApi = () => {
  if (currentCategory.value) {
    router.push({
      path: '/api-test',
      query: { 
        category: currentCategory.value.key,
        api: currentCategory.value.apis[0]?.name 
      }
    })
  }
}
</script>

<style scoped>
.docs {
  max-width: 1400px;
  margin: 0 auto;
}

.docs-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}

.header-content {
  text-align: center;
  padding: 40px 20px;
}

.header-content h1 {
  font-size: 2.5rem;
  margin-bottom: 20px;
  font-weight: 600;
}

.header-content p {
  font-size: 1.2rem;
  opacity: 0.9;
}

.sidebar-card, .content-card {
  height: fit-content;
}

.category-menu {
  border: none;
}

.api-content {
  min-height: 500px;
}

.api-item {
  margin-bottom: 40px;
}

.api-item h3 {
  color: #303133;
  margin: 0;
}

.api-info {
  margin: 20px 0;
}

.api-details {
  margin-top: 20px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.response-format h4 {
  margin: 20px 0 10px 0;
  color: #606266;
}

.response-example {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  margin-bottom: 20px;
}

.code-examples {
  margin-top: 20px;
}

.code-block {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

.no-category {
  text-align: center;
  padding: 100px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content h1 {
    font-size: 2rem;
  }
  
  .header-content p {
    font-size: 1rem;
  }
  
  .content-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .sidebar-card {
    margin-bottom: 20px;
  }
}
</style>
